package cn.zzuli.springcloud.controller;

import cn.zzuli.commons.entity.CommonResult;
import cn.zzuli.commons.entity.Payment;
import cn.zzuli.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/provider")
public class paymentController {
    @Resource
    private    PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Resource
    private DiscoveryClient discoveryClient;
    @PostMapping("/payment")
    public CommonResult create(@RequestBody Payment payment){
        CommonResult commonResult = paymentService.create(payment);
        System.out.println("-$$$$$$$$$#########*****************: "+serverPort);
        return commonResult;
    }

    @GetMapping("/payment/{id}")
    @ResponseBody
    public CommonResult getPayMentById(@PathVariable("id") Long id){

        CommonResult<Payment> payMentById = paymentService.getPayMentById(id);
        System.out.println("-$$$$$$$$$#########*****************: "+serverPort);
        return payMentById;
    }


    @GetMapping(value = "/payment/discovery")
    public Object discover(){
        List<String> services = discoveryClient.getServices();
        services.forEach(service->{
            log.info("***************service: "+service);
        });
        List<ServiceInstance> instances = discoveryClient.getInstances("PROVIDER-PAYMENT");
        instances.forEach(instance->{
            log.info(instance.getServiceId()+ " ************* "+instance.getHost()+ " ************* "+instance.getPort()+ " ************* "+instance.getUri());
        });
        return this.discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping("/payment/timeout")
    public String paymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
